package com.o2o.controller;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;

import org.springframework.stereotype.Controller;

import com.o2o.base.BaseControllerAction;
import com.o2o.content.Constant;
import com.o2o.content.CookieContent;
import com.o2o.content.SessionContent;
import com.o2o.model.area.Address;
import com.o2o.model.user.User;
import com.o2o.util.CookieUtil;
import com.o2o.util.CryptUtil;
import com.o2o.util.MD5Util;
import com.o2o.util.SecurityCodeUtil;

@Controller
public class UserControllerAction extends BaseControllerAction{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1148593517718733950L;
	
	private String email;
	
	private User user;
	
	private String chptcha;//验证码
	
	private int remember_username = 0;//记住用户名
	
	private int auto_login = 0; //记住密码
	
	private boolean needCaptcha = false; //需要验证码
	
	private String redirect = "/index";
	
	private int errorTime = 0;
	
	private String errorEmail = "error_email_"+email;
	
	
	public String userLogin(){
		if(email == null || passwd == null || email.equals("") || passwd.equals("")){
			result.put("message", "用户名或密码不能为空");
			result.put("success", false);
		}else{
			try{
				String redirectSession = (String) session.get(SessionContent.REDIRECT_URL);
				if(!redirect.equals(redirectSession)){//session中的跳转地址和浏览器带过来的redirect地址不一致，默认跳到首页
					redirect = "/index";
				}
				session.remove(SessionContent.REDIRECT_URL);
				user = userService.getUserByEmailAccount(email);
				errorTime = (Integer) session.get(errorEmail);
			}catch (Exception e) {
				
			}
			//账户名错误
			if(user == null || !MD5Util.getMD5String(passwd).equals(user.getPasswd())){
				result.put("message", "账号或密码错误，请重新输入");
				result.put("success", false);
				session.put(errorEmail, errorTime+1);
			}
			//密码正确
			if(user != null && MD5Util.getMD5String(passwd).equals(user.getPasswd())){
				session.put(SessionContent.NORMAL_USER_SESSION, user);
				session.remove(errorEmail);//清空errortime
				result.put("redirect",redirect);
				result.put("message", "登录成功");
				result.put("success", true);
				
				if(remember_username == 1){ //记住账户
					try {
						CookieUtil.addCookie(CookieContent.REMEMBER_ACCOUNT_NAME, email, response);
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
				if(auto_login == 1){
					try {
						String md5Key = MD5Util.getMD5String("_How can you find this key_"+email);;
						String encrypt = CryptUtil.Encrypt3DES(passwd,md5Key );
//						System.out.println("加密后的passwd:"+encrypt);
						int age = 30 * 24 * 3600;//一个月内记住密码
						CookieUtil.addCookie(CookieContent.AUTO_LOGIN_ACCOUNT, encrypt+","+email,age, response);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			if(errorTime > 3){
				needCaptcha = true; //登陆错误三次以上需要验证码
			}
		}
		result.put("needCaptcha", needCaptcha);
		result.put("timestamp", System.currentTimeMillis());
		return SUCCESS;
	}
	
	//退出登陆
	public String loginout(){
		session.remove(SessionContent.NORMAL_USER_SESSION);
		CookieUtil.delete(CookieContent.AUTO_LOGIN_ACCOUNT, response);
		return SUCCESS;
	}
	
	//跳到登陆页面
	public String login(){
		try {
			email = CookieUtil.findCookie(CookieContent.REMEMBER_ACCOUNT_NAME, request);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	//用户注册
	public String signup(){
		return SUCCESS;
	}
	
	private String name; //注册公司名   3-50个字符
	private String emailAccount;	//注册邮箱账号
	private String passwd;//密码 6~20个字符
	
	/**
	 * 注册参数验证
	 * @return 参数是否正确
	 */
	public boolean checkSignupRegist(){
		boolean f = false;
		if(name != null && name.trim().length() >3 && name.trim().length() < 50 &&emailAccount != null &&emailAccount.trim().matches(Constant.MEIAL_REGEX) && passwd != null && passwd.trim().length() > 5 && passwd.trim().length() < 21){
			f = true;
		}
		return f;
	}
	/**
	 * 用户注册
	 * @return
	 */
	public String signupRegist(){
		boolean checkSignupRegist = checkSignupRegist();
		if(!checkSignupRegist){
			result.put("input_status", "error");
			result.put("message", "参数输入错误");
		}else{   //参数检查正确
			try{
				boolean saveUser = userService.saveOrUpdateUser(name.trim(), passwd.trim(), emailAccount.trim(), 1, "");
				result.put("regist_status", saveUser);
				if(saveUser)message = "账号注册成功";
				else message = "账号注册失败";
				result.put("message",message);
				result.put("code", 400);
			}catch(Exception e){
				logger.error("save user error,paramter: name="+name+"&&emailAccount="+emailAccount+"&&passwd="+passwd);
				result.put("regist_status", false);
				result.put("message", "程序错误,注册失败");
				result.put("code", 503);
			}
		}
		result.put("timestamp", System.currentTimeMillis());
		return SUCCESS;
	}
	
	//图片流
	private ByteArrayInputStream imageStream;
	public String captcha(){
	//如果开启Hard模式，可以不区分大小写
	//     String securityCode = SecurityCode.getSecurityCode(4,SecurityCodeLevel.Hard, false).toLowerCase();
      
      //获取默认难度和长度的验证码
      String securityCode = SecurityCodeUtil.getSecurityCode();
      imageStream = SecurityCodeUtil.getImageAsInputStream(securityCode);
      //放入session中
      session.put(SessionContent.SESSION_SECURITY_CODE, securityCode);
		
		return SUCCESS;
	}
	
	private String userName;
	private String phoneNumber;
	private String userEmail;
	private int areaCode;
	private String address;
	/**
	 * 保存或更新用户详细资料
	 */
	public String saveOrUpdateUserProfile(){
		Address addressTmp = areaService.getAddressByAreaCode(areaCode);
		User user = (User) session.get(SessionContent.NORMAL_USER_SESSION);
		boolean saveOrUpdateUserProfile = userService.saveOrUpdateUserProfile(userName, phoneNumber, userEmail, user.getId(), addressTmp.getFullAddressDetail()+address,areaCode, address);
		result.put("saveOrUpdate", saveOrUpdateUserProfile);
		result.put("timestamp", System.currentTimeMillis());
		return SUCCESS;
	}
			
	
	

	

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	public void setUserEmail(String userEmail) {
		this.userEmail = userEmail;
	}

	public void setAreaCode(int areaCode) {
		this.areaCode = areaCode;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public ByteArrayInputStream getImageStream() {
		return imageStream;
	}

	public void setImageStream(ByteArrayInputStream imageStream) {
		this.imageStream = imageStream;
	}



	public void setName(String name) {
		this.name = name;
	}

	public void setEmailAccount(String emailAccount) {
		this.emailAccount = emailAccount;
	}

	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}

	public void setEmail(String email) {
		this.email = email;
	}




	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}



	public void setRemember_username(int remember_username) {
		this.remember_username = remember_username;
	}



	public void setAuto_login(int auto_login) {
		this.auto_login = auto_login;
	}



	public String getChptcha() {
		return chptcha;
	}



	public void setChptcha(String chptcha) {
		this.chptcha = chptcha;
	}



	public boolean isNeedCaptcha() {
		return needCaptcha;
	}



	public void setNeedCaptcha(boolean needCaptcha) {
		this.needCaptcha = needCaptcha;
	}

	public String getRedirect() {
		return redirect;
	}

	public void setRedirect(String redirect) {
		this.redirect = redirect;
	}

	public int getErrorTime() {
		return errorTime;
	}

	public void setErrorTime(int errorTime) {
		this.errorTime = errorTime;
	}

	public int getRemember_username() {
		return remember_username;
	}

	public int getAuto_login() {
		return auto_login;
	}

	public String getEmail() {
		return email;
	}
	
	
	
}
